#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os,commands,re,sys
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
import time,urllib,datetime
from tornado.options import define,options
from classify import score

define("port", default=8888, help="run on the given port", type=int)
class valid(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self,param):
        basedir = os.path.abspath(os.path.dirname(__file__))
        nsfw_command = basedir + "/classify.py"
        caffe_model = basedir + "/nsfw_model/nsfw.caffemodel"
        deploy_file = basedir + "/nsfw_model/deploy.prototxt"
        pic_path = basedir + "/pic/%s" % int(time.time())
        getImg(pic_path,param)
        text = score(pic_path,deploy_file,caffe_model)
        context = re.findall(r"0\.[0-9]+",str(text))
        self.render("index.html",context=(''.join(context)))
        #self.render("index.html",context=context)
        clean(basedir+'/pic/').delfile()
class clean:
    def __init__(self, file_url):
        self.file_url = file_url
    def delfile(self):
        f =  list(os.listdir(self.file_url))
        print("%s\n  等待清理过期文件...." % self.file_url)
        for i in range(len(f)):
            filedate = os.path.getmtime(self.file_url + f[i])
            timestamp = datetime.datetime.fromtimestamp(filedate).strftime('%Y-%m-%d')
            current_time = time.time()
            erase_time =(current_time - filedate)/60 
            if erase_time >= 5:
                try:
                    os.remove(self.file_url + f[i])
                    print(u"已删除文件：%s ： %s" %  (timestamp, f[i]))            
                except Exception as e:                                             
                    print(e) 
def getImg(path,html):
    reg = r"(.*\.[JjpPbBGg][PpnNMmIi][fFGg])"
    imgre = re.compile(reg)
    imglist = imgre.findall(html)    
    for imgurl in imglist:
        urllib.urlretrieve(imgurl, '%s' % path)
if "__name__ == __main__":
    tornado.options.parse_command_line()
    application = tornado.web.Application([(r"/valid&src=(.*)",valid)],debug=True)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

